package org.easydarwin.blogdemos;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.widget.TextView;

import org.w3c.dom.DOMException;
import org.w3c.dom.Node;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public abstract class StringUtil {


    public final static int NAME_MAX_LENGTH = 20;//姓名最大长度（中文不能超过10）

    /**
     * 产生一个随机的字符串
     *
     * @param length 字符串长度
     * @return
     */
    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 整条字符串中key关键字符显示特定颜色
     *
     * @param size            关键字大小（dp单位）
     * @param allStr          整个字符串
     * @param keyStr          关键字
     * @param color           颜色值
     * @param isStrikethrough 是否添加删除线
     * @return
     */
    public static CharSequence getSpannableString(int size, int color, String allStr, String keyStr, boolean isStrikethrough) {
        SpannableString retStr = new SpannableString(allStr);

        Locale locale = Locale.getDefault();
        String temp = allStr.toLowerCase(locale);
        int index = temp.indexOf(keyStr.toLowerCase(locale));
        if (index == -1)
            return allStr;   //new StrikethroughSpan()

        if (color != -1)
            retStr.setSpan(new ForegroundColorSpan(color), index, index + keyStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (size != -1)
            retStr.setSpan(new AbsoluteSizeSpan(size, true), index, index + keyStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        if (isStrikethrough)
            retStr.setSpan(new StrikethroughSpan(), index, index + keyStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return retStr;
    }


    /**
     * 获取url地址中的参数，用哈希列表返回结果
     *
     * @param url
     * @param isUrlEncode 表示是否需要做url转义
     * @return
     */
    public static Hashtable<String, String> getUrlParam(String url, boolean isUrlEncode) {
        Hashtable<String, String> result = new Hashtable<String, String>();
        try {
            if (!isNullOrEmpty(url)) {
                if (url.contains("?")) {
                    url = url.substring(url.indexOf("?") + 1);
                }
                String[] params = url.split("&");
                String key = "";
                String value = "";
                for (int i = 0; i < params.length; i++) {
                    if (params[i].contains("=")) {
                        key = params[i].substring(0, params[i].indexOf("="));
                        value = params[i].substring(params[i].indexOf("=") + 1);
                        if (isUrlEncode) {
                            value = java.net.URLDecoder.decode(value, "utf-8");
                        }
                        result.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 如果为今天，则显示时间，如果不是今天则显示日期
     *
     * @param context
     * @param when
     * @param fullFormat
     * @return
     */
    public static String formatTimeStampString(Context context, long when,
                                               boolean fullFormat) {
        Time then = new Time();
        then.set(when);
        Time now = new Time();
        now.setToNow();
        // Basic settings for formatDateTime() we want for all cases.
        int format_flags = DateUtils.FORMAT_NO_NOON_MIDNIGHT
                | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_AMPM;
        // If the message is from a different year, show the date and year.
        if (then.year != now.year) {
            format_flags |= DateUtils.FORMAT_SHOW_YEAR
                    | DateUtils.FORMAT_SHOW_DATE;
        } else if (then.yearDay != now.yearDay) {
            // If it is from a different day than today, show only the date.
            format_flags |= DateUtils.FORMAT_SHOW_DATE;
        } else {
            // Otherwise, if the message is from today, show the time.
            format_flags |= DateUtils.FORMAT_SHOW_TIME;
        }
        // If the caller has asked for full details, make sure to show the date
        // and time no matter what we've determined above (but still make
        // showing
        // the year only happen if it is a different year from today).
        if (fullFormat) {
            format_flags |= (DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
        }
        return DateUtils.formatDateTime(context, when, format_flags);
    }


    /**
     * 得到本地html浏览的路径
     *
     * @return
     */
    public static String getHtmlLocalPath() {
        String htmlLocalPath = "content://com.android.htmlfileprovider";
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 9)
            htmlLocalPath = "file://";
        return htmlLocalPath;
    }

    public static String getHtmlString(String content) {

        return getHtmlString(content, "");
    }

    public static String getHtmlString(String content, String className) {
        String result = "";
        if (!isNullOrEmpty(content)) {
            content = content.replace("\r", "");
                                                /*if (content.contains("\n")) {
				String[] arr = content.split("\n");
				for (int i = 0; i < arr.length; i++) {
					result += "<p  "+className+" >" + arr[i] + "</p>";
				}
				
			}else{
				result = "<p' "+className+" >" +content + "</p>";
			}*/
            content = content.replace(" ", "&nbsp;");
            content = content.replace("　", "&nbsp;");
            result = "<p " + className + " >" + content.replace("\n", "<br/>") + "</p>";
        }
        return result;
    }

    public static String getNodeValue(Node n, String def) {
        String result = def;
        try {
            if (n != null && n.hasChildNodes()) {
                result = n.getFirstChild().getNodeValue();
            }
        } catch (DOMException e) {
//            LogManager.logEx(e);
        }

        return result;
    }

    public static String getNodeAttributesValue(Node n, String parName, String def) {
        String result = def;
        try {
            if (n != null) {
                result = n.getAttributes().getNamedItem(parName).getNodeValue();
            }
        } catch (Exception e) {
//            LogManager.logEx(e);
        }

        return result;
    }

    /**
     * 生成F3目录名称
     *
     * @return
     */
    public static String getTTFolderName() {
        String folderName = "" + System.currentTimeMillis();
        return folderName;
    }

    public static boolean isNullOrEmpty(String value) {
        boolean result = false;
        result = !(value != null && !"".equalsIgnoreCase(value) && !"null".equals(value));
        return result;
    }


    public static String getDate(Context context, long dateTime) {
        int flags = 0;
        String date = "";

        Time then = new Time();
        then.set(dateTime);
        Time now = new Time();
        now.setToNow();

        if (DateUtils.isToday(dateTime)) {
            flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR;
            date = DateUtils.formatDateTime(context, dateTime, flags);
        } else if (then.year != now.year) {
            date = (String) DateFormat.format("yyyy/MM/dd", dateTime);
            // format_flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
        } else {
            flags = DateUtils.FORMAT_SHOW_DATE;
            date = DateUtils.formatDateTime(context, dateTime, flags);
        }
        return date;
    }

    /**
     * 获取指定格式的时间
     *
     * @param format
     * @return
     */
    public static String getTimeString(String format, long date) {
        Date dt = new Date(date);
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                format);
        TimeZone gmt = TimeZone.getTimeZone("GMT");//关键所在
        dateFormat.setTimeZone(gmt);
        return dateFormat.format(dt);
    }
    /**
     * MD5转码
     *
     * @param input
     * @return
     */
    public static String toMD5(String input) {
//		LogManager.d("开始对字符串进行MD5:" + input);
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            result = byte2hex(md.digest(input.getBytes("utf-8")));
        } catch (Exception e) {
            throw new RuntimeException("sign error !");
        }
        return result;
    }

    /**
     * 二行制转字符串
     */
    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }

        return hs.toString().toUpperCase();
    }

    public static String byte2hex(byte[] b, int len) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < len; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }

        return hs.toString().toUpperCase();
    }

    /**
     * 获取url连接的扩展名
     *
     * @param url
     * @return
     */
    public static String getMiniTypeFromUrl(String url) {
        String end = url.substring(url.lastIndexOf(".") + 1,
                url.length()).toLowerCase();
        if (end.indexOf("?") > -1) {
            end = end.substring(0, end.indexOf("?"));
        }
        if (end.indexOf("/") > -1) {
            end = end.substring(0, end.length() - 1);
        }

        String type = "";
        if ("m4a".equals(end) || "mp3".equals(end) || "mid".equals(end)
                || "xmf".equals(end) || "ogg".equals(end) || "wav".equals(end)) {
            type = "audio/*";
        } else if ("3gp".equals(end) || "mp4".equals(end)) {
            type = "video/*";
        } else if ("jpg".equals(end) || "gif".equals(end) || "png".equals(end)
                || "jpeg".equals(end) || "bmp".equals(end)) {
            type = "image/*";
        } else if ("apk".equals(end)) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        }
        //加入对ms office及pdf,rar,zip的判断
        else if ("doc".equals(end)) {
            type = "application/msword";
        } else if ("docx".equals(end)) {
            type = "application/msword";
        } else if ("xls".equals(end)) {
            type = "application/msexcel";
        } else if ("xlsx".equals(end)) {
            type = "application/msexcel";
        } else if ("ppt".equals(end)) {
//			type = "application/msppt";
            type = "application/vnd.ms-powerpoint";
        } else if ("pptx".equals(end)) {
            type = "application/vnd.ms-powerpoint";
        } else if ("pdf".equals(end)) {
            type = "application/pdf";
        } else if ("rar".equals(end)) {
            type = "application/rar";
        } else if ("zip".equals(end)) {
            type = "application/zip";
        }
        //判断是否链接
        else if ("html".equals(end)
                || "htm".equals(end)
                || "shtml".equals(end)
                || "asp".equals(end)
                || "aspx".equals(end)
                || "jsp".equals(end)
                || "php".equals(end)
                || "perl".equals(end)
                || "cgi".equals(end)
                || "xml".equals(end)
                || "com".equals(end)
                || "cn".equals(end)
                || "mobi".equals(end)
                || "tel".equals(end)
                || "asia".equals(end)
                || "net".equals(end)
                || "org".equals(end)
                || "name".equals(end)
                || "me".equals(end)
                || "info".equals(end)
                || "cc".equals(end)
                || "hk".equals(end)
                || "biz".equals(end)
                || "tv".equals(end)
                || "公司".equals(end)
                || "网络".equals(end)
                || "中国".equals(end)
        ) {
            type = "link";
        }
        /* 如果无法直接打开，就跳出软件列表给用户选择 */
        else {
            type = "/*";
        }

        return type;
    }

    /**
     * 获取时间戳,格式“MMddHHmmss”
     *
     * @return
     */
    public static String getCurrentTime() {
        return getCurrentTime("MMddHHmmss");
    }

    /**
     * 获取指定格式的时间戳
     *
     * @param format
     * @return
     */
    public static String getCurrentTime(String format) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                format);
        return dateFormat.format(date);
    }

    /**
     * 判断给定的字符串是不是数字
     *
     * @param strNum
     * @return
     */
    public static boolean isNumber(String strNum) {
        boolean result = false;
        if (strNum == null || "".equalsIgnoreCase(strNum)) {
            result = false;
        } else {
            Pattern pattern = Pattern.compile("^[\\-]?\\d*$");
            Matcher matcher = pattern.matcher(strNum);
            result = matcher.matches();
        }

        return result;
    }

    /**
     * 转换字符为整数
     *
     * @param strValue
     * @param def      出错的默认值
     * @return
     */
    public static int convertToInt(String strValue, int def) {
        int result = def;
        try {
            if (isNumber(strValue)) {
                result = Integer.parseInt(strValue);
            } else {
                result = def;
            }
        } catch (NumberFormatException e) {
//            LogManager.logEx(e);
            e.printStackTrace();
            result = def;
        }
        return result;
    }

    public static String getSafeXmlString(String strValue) {
        String result = "";
        if (strValue != null) {
            result = strValue.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
            result = result.replace("'", "&apos;").replace("\"", "&quot;");
        }

        return result;
    }

    /**
     * 根据60进制的字符串，解析出10进制的字符串
     *
     * @param str62
     * @return
     */
    public static String getStr10FromStr62(String str62) {
        long result = 0;
        try {
            for (int i = 0; i < str62.length(); i++) {
                int c = str62.charAt(str62.length() - i - 1);
                //0-9: 48-57    a-z:97-122     A-Z:65-90
                if (c >= '0' && c <= '9') {
                    c = c - '0';
                } else if (c >= 'a' && c <= 'z') {
                    c = c - 'a' + 10;
                } else if (c >= 'A' && c <= 'Z') {
                    c = c - 'A' + 36;
                } else {
                    result = 0;
                    break;
                }

                result += c * Math.pow(62, i);
            }
        } catch (Exception e) {
//            LogManager.logEx(e);
            e.printStackTrace();
        }
        return result + "";
    }

    public String addValue(String str1, String str2) {
        String result = "";
        int addOne = 0;
        int i;
        for (i = 0; i < str1.length() && i < str2.length(); i++) {
            String s1 = str1.charAt(str1.length() - 1 - i) + "";//.substring(str1.length()-1-i,str1.length()-1-i);
            String s2 = str2.charAt(str2.length() - 1 - i) + "";//.substring(str1.length()-1-i,str1.length()-1-i);
            int temp = (convertToInt(s1, 0) + convertToInt(s2, 0)) + addOne;
            if (temp > 9) {
                addOne = 1;
                result = s1.charAt(1) + result;
            } else {
                addOne = 0;
                result = s1 + result;
            }
            if (str1.length() >= i) {
                if (addOne == 0) {
                    result = str1.substring(0, str1.length() - i) + result;
                } else {

                }
            }


        }

        return result;
    }

    public static String getWeiboTimeStr(Date date) {
        Date today = new Date();
        long interval = today.getTime() - date.getTime();
        today.setHours(23);
        today.setMinutes(59);
        today.setSeconds(59);
        boolean isSameDay = (interval / 86400000) == 0;
        if (isSameDay) {
            if (interval < 60 * 1000) {
                return (interval / 1000) + "秒前";
            } else if (interval < 60 * 60 * 1000) {
                return (interval / (60 * 1000)) + "分前";
            } else {
                return (interval / (60 * 60 * 1000)) + "小时前";
            }
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd hh:mm",
                    Locale.ENGLISH);
            return dateFormat.format(date);
        }
    }

    public static String getWeiboTimeStr(long date) {
        return getWeiboTimeStr(new Date(date));
    }

    /**
     * 大整数相加
     *
     * @param numFirst
     * @param numSecond
     * @return
     */
    public static String BigNumPlus(String numFirst, String numSecond) {

        String rtnResult = "";
        int carryValue = 0;

        int iFirst = numFirst.length() - 1, iSecond = numSecond.length() - 1;
        for (; iFirst >= 0 && iSecond >= 0; iFirst--, iSecond--) {
            int tempFirst = numFirst.charAt(iFirst) - '0';//此处如果不减去0的ASCII码值，得到的是对应数字的ASCII码值
            int tempSecond = numSecond.charAt(iSecond) - '0';
            int tempSum = tempFirst + tempSecond + carryValue;

            if (tempSum >= 10) {
                rtnResult = (tempSum - 10) + rtnResult;
                carryValue = 1;
            } else {
                rtnResult = tempSum + rtnResult;
                carryValue = 0;
            }

        }//两数值共有长度部分相加


        //处理较长数值的数
        while (iFirst >= 0) {
            int tempSum = numFirst.charAt(iFirst--) - '0' + carryValue;
            if (tempSum >= 10) {
                rtnResult = "0" + rtnResult;//最后有进位，切当前位值为 9
                carryValue = 1;
            } else {
                rtnResult = tempSum + rtnResult;
                carryValue = 0;
            }
        }
        while (iSecond >= 0) {
            int tempSum = numSecond.charAt(iSecond--) - '0' + carryValue;
            if (tempSum >= 10) {
                rtnResult = "0" + rtnResult;
                carryValue = 1;
            } else {
                rtnResult = tempSum + rtnResult;
                carryValue = 0;
            }
        }

        if (carryValue > 0)
            rtnResult = carryValue + rtnResult;

        return rtnResult;
    }

    /**
     * 大整数相乘
     *
     * @param firstValue
     * @param secondValue
     * @return
     */
    public static String BigNumMultiply(String firstValue, String secondValue) {
        firstValue = firstValue.trim();
        secondValue = secondValue.trim();
        if ("0".equalsIgnoreCase(firstValue) || "0".equalsIgnoreCase(secondValue))
            return "0";

        ArrayList<String> mutResultItems = new ArrayList<String>();//存放单个位数字与被乘数的结果

        for (int i = secondValue.length() - 1; i >= 0; i--) {
            String resultItem = "";
            int carryValue = 0;
            int curDigit = secondValue.charAt(i) - '0';
            if (curDigit == 0) continue;
            for (int j = firstValue.length() - 1; j >= 0; j--) {
                int mutValue = curDigit * (firstValue.charAt(j) - '0') + carryValue;


                carryValue = mutValue / 10;
                mutValue = mutValue % 10;


                resultItem = mutValue + resultItem;
            }
            if (carryValue > 0)
                resultItem = carryValue + resultItem;

            for (int k = secondValue.length() - 1 - i; k > 0; k--)//补零，便于相加
            {
                resultItem = resultItem + "0";
            }
            mutResultItems.add(resultItem);
        }

        String rtnResult = "0";
        for (String value : mutResultItems) {
            rtnResult = BigNumPlus(value, rtnResult);
        }

        return rtnResult;
    }

    /**
     * 62进制转为十进制
     *
     * @param sixtyTwoValue
     * @return
     */
    public static String ConvertSixtyTwoToDecimal(String sixtyTwoValue) {
        sixtyTwoValue = sixtyTwoValue.trim();

        String rtnResult = "0";
        for (int i = 0; i < sixtyTwoValue.length(); i++) {
            String curCharValue = ConvertCharToUInt64(sixtyTwoValue.charAt(i)) + "";
            int powerLength = sixtyTwoValue.length() - i - 1;

            String powerValue = "0";
            if (powerLength > 10) {
                powerValue = "839299365868340224";// Convert.ToUInt64(Math.pow(62, 10)).ToString();
                for (int j = powerLength; j > 10; j--) {
                    powerValue = BigNumMultiply(powerValue, "62");
                }
            } else {
                powerValue = (long) Math.pow(62, powerLength) + "";
            }
            rtnResult = BigNumPlus(rtnResult, BigNumMultiply(powerValue, curCharValue));
        }

        return rtnResult;
    }


    private static int ConvertCharToUInt64(char c) {
        switch (c) {
            case '0':
                return 0;
            case '1':
                return 1;
            case '2':
                return 2;
            case '3':
                return 3;
            case '4':
                return 4;
            case '5':
                return 5;
            case '6':
                return 6;
            case '7':
                return 7;
            case '8':
                return 8;
            case '9':
                return 9;

            case 'a':
                return 10;
            case 'b':
                return 11;
            case 'c':
                return 12;
            case 'd':
                return 13;
            case 'e':
                return 14;
            case 'f':
                return 15;
            case 'g':
                return 16;
            case 'h':
                return 17;
            case 'i':
                return 18;
            case 'j':
                return 19;
            case 'k':
                return 20;
            case 'l':
                return 21;
            case 'm':
                return 22;
            case 'n':
                return 23;
            case 'o':
                return 24;
            case 'p':
                return 25;
            case 'q':
                return 26;
            case 'r':
                return 27;
            case 's':
                return 28;
            case 't':
                return 29;
            case 'u':
                return 30;
            case 'v':
                return 31;
            case 'w':
                return 32;
            case 'x':
                return 33;
            case 'y':
                return 34;
            case 'z':
                return 35;

            case 'A':
                return 36;
            case 'B':
                return 37;
            case 'C':
                return 38;
            case 'D':
                return 39;
            case 'E':
                return 40;
            case 'F':
                return 41;
            case 'G':
                return 42;
            case 'H':
                return 43;
            case 'I':
                return 44;
            case 'J':
                return 45;
            case 'K':
                return 46;
            case 'L':
                return 47;
            case 'M':
                return 48;
            case 'N':
                return 49;
            case 'O':
                return 50;
            case 'P':
                return 51;
            case 'Q':
                return 52;
            case 'R':
                return 53;
            case 'S':
                return 54;
            case 'T':
                return 55;
            case 'U':
                return 56;
            case 'V':
                return 57;
            case 'W':
                return 58;
            case 'X':
                return 59;
            case 'Y':
                return 60;
            case 'Z':
                return 61;
            default:
                break;
        }
        return 0;
    }

    static HashMap<String, SimpleDateFormat> hasSdf = null;

    public static Date parseDate(String str, String format) {
        if (str == null || "".equals(str)) {
            return null;
        }

        if (hasSdf == null) {
            hasSdf = new HashMap<String, SimpleDateFormat>();
        }
        if (!hasSdf.containsKey(format)) {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            hasSdf.put(format, sdf);
        }
        try {
            synchronized (hasSdf.get(format)) {
                // SimpleDateFormat is not thread safe
                return hasSdf.get(format).parse(str);
            }
        } catch (Exception pe) {
            return null;
            //throw new WeiboException("Unexpected format(" + str + ") returned from sina.com.cn");
        }
    }

    /**
     * 获取当前下拉刷新时间
     *
     * @param mContext
     * @return
     */
    public static String getCurRefreshTime(Context mContext) {
        return DateUtils.formatDateTime(mContext,
                System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
                        | DateUtils.FORMAT_ABBREV_ALL);
    }

//    /**
//     * 结束下拉刷新
//     *
//     * @param isRefreshing
//     * @param mPullToRefresh
//     */
//    public static boolean finishedRefresh(boolean isRefreshing, PullToRefreshListView mPullToRefresh) {
//        boolean isRefresh = isRefreshing;
//        if (isRefresh) {
//            mPullToRefresh.onRefreshComplete();
//            isRefresh = false;
//        }
//        return isRefresh;
//    }


    /**
     * 对指定字符设置颜色
     *
     * @param str   字符串
     * @param ch1   切换颜色开始的字符
     * @param ch2   切换颜色停止的字符
     * @param color 设置的颜色
     * @param tv    TextView控件
     */
    public static void setTVColor(String str, char ch1, char ch2, int color, TextView tv) {
        int a = str.indexOf(ch1); //从字符ch1的下标开始
        int b = str.indexOf(ch2) + 1; //到字符ch2的下标+1结束,因为SpannableStringBuilder的setSpan方法中区间为[ a,b )左闭右开
        SpannableStringBuilder builder = new SpannableStringBuilder(str);
        builder.setSpan(new ForegroundColorSpan(color), a, b, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(builder);
    }

    /**
     * 将时间转换为时间戳
     *
     * @param s
     * @return
     */
    public static long dateToStamp(String s) throws ParseException {
//        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
//        res = String.valueOf(ts);
        return ts;
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if (str == null || str.trim().equals("")) {
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    public static byte[] shortToByteArray(short s) {
        byte[] shortBuf = new byte[2];
        for (int i = 0; i < 2; i++) {
            int offset = (shortBuf.length - 1 - i) * 8;
            shortBuf[i] = (byte) ((s >>> offset) & 0xff);
        }
        return shortBuf;
    }

    public static short getShortBybytes(byte[] b) {
        return (short) (((b[1] << 8) | b[0] & 0xff));
    }

    public static void IntToByteArray(byte[] bb, int x, int index) {
        bb[index + 3] = (byte) (x >> 24);
        bb[index + 2] = (byte) (x >> 16);
        bb[index + 1] = (byte) (x >> 8);
        bb[index + 0] = (byte) (x >> 0);
    }

    // int -> byte[4]
    public static byte[] intToByteArray(int integer) {
        byte[] byteArray = new byte[4];

        for (int n = 0; n < 4; n++) {
            int offset = n * 8;
            byteArray[n] = (byte) ((integer >> offset) & 0xff);
        }

        return (byteArray);
    }

    public static int byteToInt(byte b1, byte b2, byte b3, byte b4) {
        int s = 0;
        s += (b1 & 0xFF) << (8 * 0);
        s += (b2 & 0xFF) << (8 * 1);
        s += (b3 & 0xFF) << (8 * 2);
        s += (b4 & 0xFF) << (8 * 3);
        return s;
    }

    public static String byteToString(byte b1) {
        String res = "";
        res = (((b1 & 0xFF) << (8 * 0)) - 48) + "";
        return res;
    }

    private static int mixSingle(int a, int b) {
        // C = A + B - (A * B >> 0x10) 混音算法
        int mix = a + b - (a * b >> 0x10);
        mix = (mix > 32767) ? 32767 : mix;
        mix = (mix < -32768) ? -32768 : mix;
        return mix;
    }

    public static byte[] mix(byte[] a1, byte[] a2) {
        byte[] mixBytes = new byte[a1.length];

        short[] source = new short[a1.length / 2];
        ByteBuffer.wrap(a1).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(source);
        short[] target = new short[a2.length / 2];
        ByteBuffer.wrap(a2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(target);

        for (int i = 0; i < source.length; i++) {
            int mix = mixSingle(source[i], target[i]);
            mixBytes[2 * i] = (byte) (mix & 0xff);
            mixBytes[2 * i + 1] = (byte) ((mix >> 8) & 0xFF);
        }
        return mixBytes;
    }

    public static long calcChkSum(byte[] pBuffer) {
        short[] pData = new short[pBuffer.length / 2];
        ByteBuffer.wrap(pBuffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(pData); // 数组类型转换

        long dwChkSum = 0;
        for (int j = 0; j < pData.length; j++) {
            dwChkSum = dwChkSum + pData[j] & 0xffff;
        }
        return dwChkSum;
    }

    public static String getHexString(byte b) {
        String s = Integer.toHexString(b & 0xFF).toUpperCase();
        if (s.length() == 1) {
            return "0" + s;
        } else {
            return s;
        }
    }

    public static String printBuffer(byte[] bytes, int start, int len) {
        String str = "";
        int length = len;
        if (len >= bytes.length)
            length = bytes.length;

        for (int i = start; i < length; i++) {
//            str += Byte.toString(bytes[i]) + " ";
            str += getHexString(bytes[i]) + " ";
        }
        return str;
    }

    public static String printBuffer(short[] shorts, int start, int len) {
        String str = "";
        for (int i = start; i < len; i++)
            str += Short.toString(shorts[i]) + " ";
        return str;
    }

    public static int getStringRealLength(String str) {
        String str1;

        try {
            str1 = new String(str.getBytes("GBK"), "iso-8859-1");
            return str1.length();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } // GB2312

        return 0;
    }

    public static String cutString(String s, int n) {
        try {
            if (s != null && "".equals(s)) {
                s = new String(s.getBytes(), "GBK");
            }
            StringBuffer buffer = new StringBuffer();
            if (n != 0 && n < s.getBytes("GBK").length) {

                for (int i = 0; i < n; i++) {
                    char c = s.charAt(i);
                    buffer.append(c);
                    // System.out.println("buffer=" + buffer.toString());
                    if (isChineseChar(c)) {
                        --n;
                    }
                }
            }
            return buffer.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    private static boolean isChineseChar(char c) {
        try {
            return String.valueOf(c).getBytes("GBK").length > 1;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    // 对参数进行校验
    public static boolean checkIpaddr(String ipAddress) {
        String ip = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    public static boolean checkNumber(String str, int maxValue, int minValue) {
        boolean bRet = false;

        if (str == null || str.length() == 0) {
            return bRet;
        }

        if (str.charAt(0) == '0') {
            return bRet;
        }

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                return bRet;
            }
        }

        if (str.length() > 9 || str.length() == 0) {
            return bRet;
        }
        int checkData = Integer.parseInt(str);
        if (checkData <= maxValue && checkData >= minValue) {
            bRet = true;
        }
        return bRet;
    }

    public static boolean checkNumber(String str) {
        boolean bRet = false;

        if (str == null || str.length() == 0) {
            return bRet;
        }

        if (str.charAt(0) == '0') {
            return bRet;
        }

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                return bRet;
            }
        }

        if (str.length() > 16 || str.length() == 0) {
            return bRet;
        }

        bRet = true;
        return bRet;
    }

    public static boolean checkConferenceNumber(String str, int maxValue, int minValue) {
        boolean bRet = false;

        if (TextUtils.isEmpty(str) || str.charAt(0) != '0') {
            return bRet;
        }
        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                return bRet;
            }
        }

        if (str.length() > 16 || str.length() == 0) {
            return bRet;
        }
//        int checkData = Integer.parseInt(str);
//        if (checkData <= maxValue && checkData >= minValue) {
//            bRet = true;
//        }
        return true;
    }

    public static String getValidNumber(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != '0'){
                return str.substring(i);
            }
        }
        return null;
    }

    public static String getNoneNullString(String str) {
        for (int i = 0; i < str.length(); i++) {
            if ((str.charAt(i) != '0') && (str.charAt(i) != ' ')){
                return str.substring(i);
            }
        }
        return null;
    }

    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);//左补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }
}
